package com.jinlejia.erp.ui.mine.contract;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.LoginExamineAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityAuditLoginBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.weight.CustomToast;
import com.weight.IconToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class AuditLoginActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private String[] headers = {"状态", "日期"};
    private String[] checkState = {"全部", "待审核", "已审核", "已驳回"};
    private List<View> popupViews = new ArrayList<>();
    private GirdDropDownAdapter stateAdapter;

    private ActivityAuditLoginBinding binding;
    private ProgressDialog progressDialog;
    private String strstate = "0";
    private int pageIndex = 1;
    private JSONObject jsonObject = new JSONObject();
    private boolean mLoadingLock = false;//是否正在加载
    private LoginExamineAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_audit_login);
        binding.setEvent(this);
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        progressDialog = new ProgressDialog(this, "请稍后...", false);
        //region init state menu
        final ListView stateView = new ListView(this);
        stateAdapter = new GirdDropDownAdapter(this, Arrays.asList(checkState));
        stateView.setAdapter(stateAdapter);
        stateView.setOnItemClickListener((parent, view, position, id) -> {
            binding.dropDownMenu.setTabText(checkState[position]);
            binding.dropDownMenu.closeMenu();
            stateAdapter.setCheckItem(position);
            if (position >= 0) {
                strstate = String.valueOf(position);
            }
            getData();
            if (!progressDialog.isShowing()){
                progressDialog.show();
            }
        });
        //endregion

        //region init time menu
        View timeView = LayoutInflater.from(this).inflate(R.layout.layout_dropmenu_time, null);
        final TextView earliestTime = timeView.findViewById(R.id.earliest_time);
        final TextView latestTime = timeView.findViewById(R.id.latest_time);
        TextView cinfirm = timeView.findViewById(R.id.cinfirm);
        earliestTime.setOnClickListener(v -> {
            TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                    .setType(Type.YEAR_MONTH_DAY)
                    .setTitleStringId("最早时间")
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.yellow))
                    .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                    .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                    .setCallBack((timePickerView, millseconds) -> {
                        earliestTime.setText(DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                        jsonObject.put("applyTimeMin", DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                    })
                    .build();
            visitFloorPicker.show(getSupportFragmentManager(), "year_month");
        });
        latestTime.setOnClickListener(v -> {
            TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                    .setType(Type.YEAR_MONTH_DAY)
                    .setTitleStringId("最晚时间")
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.yellow))
                    .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                    .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                    .setCallBack((timePickerView, millseconds) -> {
                        latestTime.setText(DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                        jsonObject.put("applyTimeMax", DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                    })
                    .build();
            visitFloorPicker.show(getSupportFragmentManager(), "year_month");
        });
        cinfirm.setOnClickListener(v -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date data1 = null,data2 = null;
            try {
                data1 = dateFormat.parse(earliestTime.getText().toString());
                data2= dateFormat.parse(latestTime.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(earliestTime.getText()) || TextUtils.isEmpty(latestTime.getText())){
                CustomToast.showToast(AuditLoginActivity.this,"请至少选择一个时间节点",1500);
            }else if (data1.getTime()>data2.getTime()){
                CustomToast.showToast(AuditLoginActivity.this,"最早时间不得大于最晚时间",1500);
            }else{
                binding.dropDownMenu.closeMenu();
                if (!progressDialog.isShowing()){
                    progressDialog.show();
                }
                getData();
            }
        });
        //endregion


        popupViews.add(stateView);
        popupViews.add(timeView);
        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setHasFixedSize(true);
        binding.recyclerView.enableAutoLoadMore(this);
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        adapter = new LoginExamineAdapter(dataList);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((view, o) -> adapter.addChecked((Map<String, Object>) o));
        adapter.setOnaddLastListener(new LoginExamineAdapter.OnaddCheckLatLintener() {
            @Override
            public void addcheck(boolean isAllcheck) {
                    binding.idCheckBox.setChecked(isAllcheck);
            }
        });
        adapter.addCheckedById(getIntent().getStringExtra("id"));
        //全选操作
        binding.llAllCheck.setOnClickListener(v -> {
            if (adapter.isToBeReviewed()){
                if (!binding.idCheckBox.isChecked()) {
                    binding.idCheckBox.setChecked(true);
                    adapter.allChecked(true);
                } else {
                    binding.idCheckBox.setChecked(false);
                    adapter.allChecked(false);
                }
            }else{
                CustomToast.showToast(AuditLoginActivity.this,"当前没有待审核数据",1500);
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.tvReject://驳回
                if (TextUtils.isEmpty(adapter.getSelectId())){
                    CustomToast.showToast(AuditLoginActivity.this,"请先选择一条待审核记录",1500);
                }else{
                    examineLoginApply("3");
                }
                break;
            case R.id.tvAdopt://审核通过
                if (TextUtils.isEmpty(adapter.getSelectId())){
                    CustomToast.showToast(AuditLoginActivity.this,"请先选择一条待审核记录",1500);
                }else {
                    examineLoginApply("2");
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageIndex = 1;
        getData();
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0){
            if (mLoadingLock) {
                return;
            }
            pageIndex++;
            adapter.addFooter("加载中");
            getData();
        }else{
            adapter.addFooter(R.string.is_all);
        }

    }

    //region 请求登录审核列表数据
    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageSize", 10);
        jsonObject.put("state", strstate);

        OkHttpUtils.postString()
                .url(ApiConfig.APPLU_LOGIN_LIST)
                .content(jsonObject.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        if (progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                        mLoadingLock = false;
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        if (progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(AuditLoginActivity.this, response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            ArrayList<Map<String, Object>> dataList = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (pageIndex == 1) {
                                adapter.setData(dataList);
                            } else {
                                adapter.addData(dataList);
                                binding.idCheckBox.setChecked(false);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            pageIndex--;
                            adapter.addFooter("已经没有更多");
                        }
                        if (adapter.getFooters().size() > 0) {
                            adapter.removeAllFooters();
                        }
                        mLoadingLock = false;
                    }
                });


    }
    //endregion

    //region 审核驳回提交接口
    private void examineLoginApply(String state) {
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        JSONObject json = new JSONObject();
        json.put("state", state);
        json.put("ids", adapter.getSelectId());

        OkHttpUtils.postString()
                .url(ApiConfig.EXAMINELOGINAPPLY)
                .content(json.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(AuditLoginActivity.this, response)) {
                            IconToast.showToast(AuditLoginActivity.this, R.mipmap.ic_success, "操作成功", 1500);
                            getData();
                            binding.idCheckBox.setChecked(false);
                        }
                    }
                });
    }
    //endregion


}
